package com.example.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.example.mall.client.OrderFeignClient;
import com.example.mall.constants.BaseConstants;
import com.example.mall.domain.AlipayInfo;
import com.example.mall.domain.Order;
import com.example.mall.domain.PayOrder;
import com.example.mall.dto.PayApplyDto;
import com.example.mall.exception.GlobalCustomerException;
import com.example.mall.result.JSONResult;
import com.example.mall.service.IAlipayInfoService;
import com.example.mall.service.IPayOrderService;
import com.example.mall.service.IPayService;
import com.example.mall.to.PlaceProductOrderTo;
import com.example.mall.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;

/**
 * @Author: xxxliu
 * @CreateTime: 2025-06-03
 * @Version: 1.0
 */
@Service
@Slf4j
@Transactional
public class PayServiceImpl implements IPayService {

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private OrderFeignClient orderFeignClient ;

    @Autowired
    private IPayOrderService payOrderService;

    //创建配置
    public Config getOptions(AlipayInfo alipayInfo){
        Config config = new Config();
        config.protocol = alipayInfo.getProtocol();
        config.gatewayHost = alipayInfo.getGatewayHost();
        config.signType = alipayInfo.getSignType();
        config.appId = alipayInfo.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = alipayInfo.getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = alipayInfo.getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = alipayInfo.getNotifyUrl();
        return config;
    }

    @Override
    public String apply(PayApplyDto payApplyDto) {
        AssertUtil.isEquals(String.valueOf(payApplyDto.getPayType()), String.valueOf(BaseConstants.Pay.PAY_TYPE_ALIPAY),"仅仅支持阿里支付");

        //查询订单
        AssertUtil.isNotEmpty(payApplyDto.getOrderNo(),"订单号不可为空");

        PayOrder payOrder = payOrderService.selectByOrderNo(payApplyDto.getOrderNo());

        if(payOrder == null){
            //支付单获取失败，通过Fiegn查询
            JSONResult jsonResult = orderFeignClient.selectByOrderNo(payApplyDto.getOrderNo());
            AssertUtil.isTrue(jsonResult.isSuccess(),"支付单获取失败");

            Order order = JSON.parseObject(JSON.toJSONString(jsonResult.getData()), Order.class);

            payOrder = payOrderService.savePayOrder(order);
        }
        AssertUtil.isNotNull(payOrder,"支付单获取失败");

        log.info("支付申请 {}",payOrder);

        //查询ali支付配置参数
        AlipayInfo alipayInfo = alipayInfoService.queryAlipayInfoList().get(0);
        //配置对象
        Config config = getOptions(alipayInfo);

        Factory.setOptions(config);
        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            //自定义的业务参数
            //"userId="+LoginContext.getLogin().getId()+"&relationId="+courseOrder.getCourseId()
            String passbackParams = URLEncoder.encode(payOrder.getExtParams(),"UTF-8");

            //构建支付同步回跳页面

            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .optional("passback_params",passbackParams) //自定义参数，异步回调原样返回
                    .pay(payOrder.getSubject(), payApplyDto.getOrderNo(),payOrder.getAmount().toString(), payApplyDto.getCallUrl()
                    );
            // 3. 处理响应或异常
            log.info("支付申请结果 body{}",response.body);
            if (ResponseChecker.success(response)) {
                log.info("支付申请成功");
            } else {
                log.info("支付申请失败 {}",response.body);
            }
            //返回结果
            return response.body;
        } catch (Exception e) {
            log.error("支付申请异常 {}",e.getMessage());
        }
        return null;
    }

    @Override
    public void closeOrder(PlaceProductOrderTo placeProductOrderTo) {
        log.info("支付关单申请...");
        //查询ali支付配置参数
        AlipayInfo alipayInfo = alipayInfoService.queryAlipayInfoList().get(0);
        //配置对象
        Config config = getOptions(alipayInfo);

        Factory.setOptions(config);
        try {
            // 2. 发起API调用
            AlipayTradeCloseResponse response = Factory.Payment.Common().close(placeProductOrderTo.getOrderNo());
            if(response.code.equals("10000")){

                log.info("关单成功");
            } else {
                log.info("关单失败 {} , {} ",response.msg,response.subMsg);
            }
        } catch (Exception e) {
            log.error("支付申请异常 {}",e.getMessage());
        }
    }
}
